from django.core.cache import cache
from django.conf import settings
# Create your views here.
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework.decorators import action

from user import serializers
from user import models
from lufflyapi.utils.response import APIResponse

from lufflyapi.libs.tencent import get_code, send_code
from .throttlings import SMSThrottle


class LoginView(ViewSet):

    @action(methods=['post'], detail=False)
    def login(self, request):

        user_serializer = serializers.LoginUserModelSerializer(data=request.data)
        if user_serializer.is_valid():
            token = user_serializer.context['token']
            username = user_serializer.context['user'].username
            return APIResponse(result=dict(token=token, username=username))

        return APIResponse(code=101, msg='login fail', result=user_serializer.errors)

    @action(methods=['get'], detail=False)
    def check_telephone(self, request, *args, **kwargs):
        """
        检查手机号是否存在
        """
        telephone = request.query_params.get('telephone')
        user = models.User.objects.filter(telephone=telephone).first()
        if user:
            return APIResponse(result="手机号存在")

        return APIResponse(code=101, msg='error search telephone', result='手机号不存在')

    @action(methods=['post'], detail=False)
    def telephone_login(self, request, *args, **kwargs):
        """
        手机号+验证码的登录接口
        """
        code_serializer = serializers.CodeUserModelSerializer(data=request.data)
        if code_serializer.is_valid():
            token = code_serializer.context['token']
            username = code_serializer.context['user'].username
            return APIResponse(result={'token': token, 'username': username})
        else:
            return APIResponse(code=101, msg='error', result=code_serializer.errors)


class SMSSendView(ViewSet):
    throttle_classes = [SMSThrottle]

    @action(methods=['get'], detail=False)
    def send(self, request, *args, **kwargs):
        """
        发送验证码接口
        """
        code = get_code()
        telephone = request.query_params.get('telephone')
        cache.set(settings.CODE_CACHE_KEY % {"telephone": telephone}, code, 180)  # 缓存
        telephone = settings.TELEPHONE_HEAD + telephone
        is_success = send_code(telephone, code)
        if is_success:
            return APIResponse(result="验证码发送成功")

        return APIResponse(code=101, msg='error send code', result='验证码发送失败')


# class RegisterView(ViewSet):
#
#     @action(['post'], detail=False)
#     def register(self, request, *args, **kwargs):
#
#         register_serializer = serializers.RegisterUserModelSerializer(data=request.data)
#         if register_serializer.is_valid():
#             register_serializer.save()
#             return APIResponse(result='注册成功')
#
#         return APIResponse(code=101, msg='register fail', result='注册失败')


# class RegisterView(GenericViewSet):
#     queryset = models.User.objects.all()
#     serializer_class = serializers.RegisterUserModelSerializer
#
#     @action(['post'], detail=False)
#     def register(self, request, *args, **kwargs):
#         register_serializer = self.get_serializer(data=request.data)
#         if register_serializer.is_valid():
#             register_serializer.save()
#             return APIResponse(result='注册成功')
#
#         return APIResponse(code=101, msg='register fail', result='注册失败')

class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializers.RegisterUserModelSerializer

    @action(['post'], detail=False)
    def register(self, request, *args, **kwargs):
        response = self.create(request, *args, **kwargs)
        return APIResponse(result=response.data)
